/*
	Copyright (C) 1994 Sean Luke

	COWSTestBench.m
	Version 1.0
	Sean Luke
	
	This object is just a front end to make the interpreter look pretty in this
	example program...
	
*/

#import "COWSTestBench.h"
#import "COWSInterpreter.h"
#import <appkit/appkit.h>
#import "COWSLibrary.h"
#import "COWSStringNode.h"
#import <string.h>

@implementation COWSTestBench

- print:sender
{
	[interpreter printProgram];
	[interpreter printDictionaries];
	return self;
}

- setTimedEntry:sender
{
	[interpreter setForeground: (BOOL)[[foreground cellAt:0:0] intValue]];
	[interpreter setLocked: [locked intValue]];
	[interpreter setTimedEntrySpeed:[timedEntry floatValue]];
	[interpreter setRepeats:[repeats intValue]];
	[self revertTimedEntry:sender];					// makes fields pretty
	return self;
}

- revertTimedEntry:sender
{
	[foreground selectCellAt:
		([interpreter foreground] ? 0 : 1):0];
	[timedEntry setFloatValue:[interpreter timedEntrySpeed]];
	[repeats setIntValue:[interpreter repeats]];
	[locked setIntValue:[interpreter locked]];
	return self;
}

- load:sender
{
	int x=[program textLength];
	char prog[x+1];
	
	[program getSubstring:prog start:0 length:x];
	prog[x]='\0';							// some bug in Text object
	[interpreter clearLibraryFunctions];
	[interpreter addLibrary:library];
	[interpreter addLibrary:jungle];
	[interpreter addLibrary:ipc];
	[interpreter addLibrary:array];
	[interpreter setDelegate:self];
	if ([interpreter setProgram:prog]>=0)
		{
		printf ("LOADED PROGRAM\n");
		}
	else printf ("ERROR PARSING PROGRAM\n");
	return self;
}

- execute:sender
{
	id arg_list=[[COWSArgumentList alloc] init];
	int m=1;
	id args=[[COWSArgumentList alloc] init];
		
	while (m<=6&&strlen([[matrix cellAt:m:0] stringValue]))
		{
		id temp=[[COWSStringNode alloc] init];
		[temp setString:[[matrix cellAt:m:0] stringValue]];
		[arg_list push:temp]; 
		m++;
		}
	
	// this is in wrong order...so reverse it...
	
	while([arg_list top]!=NULL)
		{
		[args push:[arg_list pop]];
		}
	[arg_list free];
		
	[interpreter interpretFunction:[[matrix cellAt:0:0] stringValue]
		arguments:args];
	[args free];
	return self;
}

- loadAndExecute:sender
{
	[self load:self];
	[self execute:self];
	return self;
}

- stop:sender
{
	printf("\nSTOPPED PROGRAM\n");
	[interpreter stopInterpreting];
    return self;
}


- finishedInterpreting:(const char*)returnValue:(int)thisMessage:sender
{
	printf("\n FINISHED PROGRAM message: %d  return:  %s\n",thisMessage,returnValue);
	return self;
}

- errorInterpreting:(int) thisError:(const char*)thisFunction:
	(int)thisPosition:(const char*)thisString:sender
{
	// doesn't do anything right now...my errors are printed to stdout.
	return self;
}


@end
